import {
  ref,
  reactive,
  watch,
  onUnmounted,
  onScopeDispose,
  computed,
  watchEffect,
} from "vue";
import { generateChallenge, generateAIAnswer } from "./challengeGenerator";

export function useAIBattle(emit) {
  const phase = ref("selection");
  const pvpMode = ref("matchmaking");
  const battleMode = ref("solo");
  const selectedAI = ref(null);
  const opponent = ref(null);
  const totalRounds = ref(5);
  const timeRemaining = ref(15);
  const currentChallenge = ref(null);
  const battleResult = ref(null);
  const finalTestResult = ref(null);
  const reactionStartTime = ref(null);
  const challengeStartTime = ref(null);
  const showPlayerAnswer = ref(false);
  const showAIAnswer = ref(false);
  const battleStarted = ref(false);
  const timerRef = ref(null);
  const playerHasAnswered = ref(false);

  const aiStatus = ref("waiting");
  const aiThinkingProgress = ref(0);
  const aiAnswerTime = ref(null);

  const currentStats = reactive({
    round: 1,
    player1Score: 0,
    player2Score: 0,
    playerTeamScore: 0,
    aiTeamScore: 0,
    playerScore: 0,
    aiScore: 0,
    player1Correct: 0,
    player2Correct: 0,
    playerTeamCorrect: 0,
    aiTeamCorrect: 0,
    playerCorrect: 0,
    aiCorrect: 0,
    timeRemaining: 15,
  });

  const battleData = computed(() => {
    if (pvpMode.value === "battle") {
      return {
        playerScore: currentStats.player1Score,
        opponentScore: currentStats.player2Score,
        opponentName: opponent.value?.name || "对手",
        opponentAvatar: opponent.value?.avatar || "🤖",
      };
    } else if (battleMode.value === "team") {
      return {
        playerScore: currentStats.playerTeamScore,
        opponentScore: currentStats.aiTeamScore,
        opponentName: `${selectedAI.value?.name}团队`,
        opponentAvatar: selectedAI.value?.emoji || "🤖",
      };
    } else {
      return {
        playerScore: currentStats.playerScore,
        opponentScore: currentStats.aiScore,
        opponentName: selectedAI.value?.name || "AI",
        opponentAvatar: selectedAI.value?.emoji || "🤖",
      };
    }
  });

  const startSoloBattle = (ai) => {
    selectedAI.value = ai;
    battleMode.value = "solo";
    phase.value = "preparation";
    totalRounds.value = 5;
    timeRemaining.value = 15;
  };

  const startTeamBattle = (ai) => {
    selectedAI.value = ai;
    battleMode.value = "team";
    phase.value = "preparation";
    totalRounds.value = 6;
    timeRemaining.value = 20;
  };

  const startBattle = () => {
    pvpMode.value = "battle";
    opponent.value = { id: "player2", name: "Human Player", avatar: "🧑‍🚀" };
    phase.value = "preparation";
  };

  const startBattleFromPreparation = () => {
    phase.value = "battle";
    battleStarted.value = true;
    currentStats.round = 1;
    Object.assign(currentStats, {
      player1Score: 0,
      player2Score: 0,
      playerTeamScore: 0,
      aiTeamScore: 0,
      playerScore: 0,
      aiScore: 0,
      player1Correct: 0,
      player2Correct: 0,
      playerTeamCorrect: 0,
      aiTeamCorrect: 0,
      playerCorrect: 0,
      aiCorrect: 0,
    });
    startNewRound();
  };

  const handleAnswer = (answer) => {
    if (!currentChallenge.value || currentChallenge.value.completed) {
      return;
    }

    let timeToAnswer = 0;
    if (currentChallenge.value.type === "reaction" && reactionStartTime.value) {
      timeToAnswer = (Date.now() - reactionStartTime.value) / 1000;
    } else if (challengeStartTime.value) {
      timeToAnswer = (Date.now() - challengeStartTime.value) / 1000;
    }

    currentChallenge.value.playerAnswer = answer;
    currentChallenge.value.timeToAnswer = timeToAnswer;
    currentChallenge.value.completed = true;

    showPlayerAnswer.value = true;
    playerHasAnswered.value = true;

    const isCorrect =
      String(answer) === String(currentChallenge.value.correctAnswer);
    const basePoints = battleMode.value === "team" ? 25 : 20;
    const points = isCorrect
      ? currentChallenge.value.type === "reaction"
        ? Math.max(10, basePoints + 15 - timeToAnswer * 2)
        : basePoints
      : 0;

    if (battleMode.value === "team") {
      currentStats.playerTeamScore += points;
      currentStats.playerTeamCorrect += isCorrect ? 1 : 0;
    } else {
      currentStats.playerScore += points;
      currentStats.playerCorrect += isCorrect ? 1 : 0;
    }
  };

  const startNewRound = () => {
    const challenge = generateChallenge(
      currentStats.round,
      battleMode.value === "team",
      selectedAI.value
    );
    currentChallenge.value = challenge;
    showPlayerAnswer.value = false;
    showAIAnswer.value = false;
    playerHasAnswered.value = false;
    aiStatus.value = "thinking";
    aiThinkingProgress.value = 0;
    aiAnswerTime.value = null;
    timeRemaining.value = battleMode.value === "team" ? 20 : 15;
    currentStats.timeRemaining = timeRemaining.value;

    challengeStartTime.value = Date.now();
    if (challenge.type === "reaction") {
      const delay = 2000 + Math.random() * 3000;
      setTimeout(() => {
        reactionStartTime.value = Date.now();
      }, delay);
    }

    const aiResult = generateAIAnswer(challenge, selectedAI.value);

    const aiThinkTime = aiResult.time;
    const thinkingInterval = setInterval(() => {
      const elapsed = Date.now() - challengeStartTime.value;
      const progress = Math.min((elapsed / aiThinkTime) * 100, 100);
      aiThinkingProgress.value = progress;
      if (progress >= 100) {
        clearInterval(thinkingInterval);
        aiStatus.value = "answering";
      }
    }, 50);

    setTimeout(() => {
      currentChallenge.value.aiAnswer = aiResult.answer;
      showAIAnswer.value = true;
      aiStatus.value = "completed";
      aiAnswerTime.value = aiResult.time / 1000;
      clearInterval(thinkingInterval);
    }, aiThinkTime);
  };

  const finishBattle = () => {
    battleStarted.value = false;

    let playerScore, opponentScore, correctAnswers, rounds, testTypeName;

    if (pvpMode.value === "battle") {
      playerScore = currentStats.player1Score;
      opponentScore = currentStats.player2Score;
      correctAnswers = currentStats.player1Correct;
      rounds = totalRounds.value;
      testTypeName = "真人对战";
    } else if (battleMode.value === "team") {
      playerScore = currentStats.playerTeamScore;
      opponentScore = currentStats.aiTeamScore;
      correctAnswers = currentStats.playerTeamCorrect;
      rounds = totalRounds.value;
      testTypeName = "AI团队对战";
    } else {
      playerScore = currentStats.playerScore;
      opponentScore = currentStats.aiScore;
      correctAnswers = currentStats.playerCorrect;
      rounds = totalRounds.value;
      testTypeName = "AI对战综合测试";
    }

    const playerWins = playerScore > opponentScore;
    const isDraw = playerScore === opponentScore;

    battleResult.value = playerWins ? "victory" : isDraw ? "draw" : "defeat";
    phase.value = "result";

    const finalScore = Math.min(
      100,
      Math.round((correctAnswers / rounds) * 100)
    );

    finalTestResult.value = {
      id: Date.now().toString(),
      testType: testTypeName,
      score: finalScore,
      maxScore: 100,
      date: new Date(),
      duration:
        rounds *
        (pvpMode.value === "battle"
          ? 15
          : battleMode.value === "team"
          ? 20
          : 15),
      percentile: Math.max(
        1,
        Math.min(99, finalScore + Math.random() * 20 - 10)
      ),
      details: {
        battleMode: true,
        pvpMode: pvpMode.value === "battle",
        teamMode: battleMode.value === "team",
        opponent:
          pvpMode.value === "battle" ? opponent.value?.id : selectedAI.value.id,
        winner: playerWins ? "player" : "opponent",
        rounds: rounds,
        playerScore: playerScore,
        opponentScore: opponentScore,
        playerCorrect: correctAnswers,
        opponentCorrect:
          pvpMode.value === "battle"
            ? currentStats.player2Correct
            : battleMode.value === "team"
            ? currentStats.aiTeamCorrect
            : currentStats.aiCorrect,
      },
    };
  };

  const resetBattle = () => {
    phase.value = "selection";
    selectedAI.value = null;
    battleStarted.value = false;
    battleResult.value = null;
    finalTestResult.value = null;
    currentChallenge.value = null;
    reactionStartTime.value = null;
    challengeStartTime.value = null;
    battleMode.value = "solo";
    pvpMode.value = "matchmaking";
    opponent.value = null;

    Object.assign(currentStats, {
      round: 1,
      player1Score: 0,
      player2Score: 0,
      playerTeamScore: 0,
      aiTeamScore: 0,
      playerScore: 0,
      aiScore: 0,
      player1Correct: 0,
      player2Correct: 0,
      playerTeamCorrect: 0,
      aiTeamCorrect: 0,
      playerCorrect: 0,
      aiCorrect: 0,
      timeRemaining: 15,
    });
  };

  const handleComplete = () => {
    emit("complete", finalTestResult.value);
  };

  watch(timeRemaining, (newTime) => {
    if (
      newTime === 0 &&
      phase.value === "battle" &&
      !currentChallenge.value.completed
    ) {
      handleAnswer("timeout");
    }
  });

  watch(battleStarted, (isStarted) => {
    if (isStarted) {
      timerRef.value = setInterval(() => {
        if (timeRemaining.value > 0) {
          timeRemaining.value--;
        } else {
          clearInterval(timerRef.value);
        }
      }, 1000);
    } else {
      clearInterval(timerRef.value);
    }
  });

  onUnmounted(() => {
    clearInterval(timerRef.value);
  });

  watchEffect(() => {
    if (playerHasAnswered.value && showAIAnswer.value) {
      const basePoints = battleMode.value === "team" ? 25 : 20;
      const aiIsCorrect =
        String(currentChallenge.value.aiAnswer) ===
        String(currentChallenge.value.correctAnswer);
      const aiPoints = aiIsCorrect ? basePoints : 0;

      if (battleMode.value === "team") {
        currentStats.aiTeamScore += aiPoints;
        currentStats.aiTeamCorrect += aiIsCorrect ? 1 : 0;
      } else {
        currentStats.aiScore += aiPoints;
        currentStats.aiCorrect += aiIsCorrect ? 1 : 0;
      }

      setTimeout(() => {
        if (currentStats.round >= totalRounds.value) {
          finishBattle();
        } else {
          currentStats.round++;
          startNewRound();
        }
      }, 2000);
    }
  });

  return {
    phase,
    pvpMode,
    battleMode,
    selectedAI,
    opponent,
    totalRounds,
    timeRemaining,
    currentChallenge,
    battleResult,
    finalTestResult,
    reactionStartTime,
    challengeStartTime,
    showPlayerAnswer,
    showAIAnswer,
    battleStarted,
    aiStatus,
    aiThinkingProgress,
    aiAnswerTime,
    currentStats,
    battleData,
    startSoloBattle,
    startTeamBattle,
    startBattle,
    handleAnswer,
    resetBattle,
    handleComplete,
    startBattleFromPreparation,
  };
}
